/*
Copyright © 2023 taiping
*/

package templates

var Service = `
package service

import (
	"errors"
	"gorm.io/gorm/clause"
	"wit-admin-go/business/dto"
	"wit-admin-go/business/model"
	"wit-admin-go/system/utils"
)

type {{.M1}}Service struct{}

var {{.M2}}Service = new({{.M1}}Service)

// PostCreate{{.M2}}  创建{{.M3}}
func (us *{{.M1}}Service) PostCreate{{.M2}}({{.M1}} dto.{{.M2}}) (err error) {
	{{.M1}}.CreateTime = time.Now()
	return utils.DB.Create(&{{.M1}}).Error
}

// PutUpdate{{.M2}} 修改{{.M3}}
func (us *{{.M1}}Service) PutUpdate{{.M2}}({{.M1}} dto.{{.M2}}) (err error) {
	_, errN := us.Get{{.M2}}ById({{.M1}}.Id)
	if errN != nil {
		return errN
	}
	{{.M1}}s := new(model.{{.M2}})
	{{.M1}}.UpdateTime = time.Now()
	return utils.DB.Model(&{{.M1}}s).Where("id = ?", {{.M1}}.Id).Updates({{.M1}}).Error
}

// Get{{.M2}}ById 通过ID查询数据
func (us *{{.M1}}Service) Get{{.M2}}ById(id string) ({{.M1}} model.{{.M2}}, err error) {
	err = utils.DB.First(&{{.M1}}, "id = ?", id).Error
	if err != nil {
		return {{.M1}}, errors.New("数据没找到")
	}
	return {{.M1}}, err
}

// Get{{.M2}}List 获取所有数据
func (us *{{.M1}}Service) Get{{.M2}}List(page *dto.{{.M2}}Page) (*[]model.{{.M2}}, int64) {
	{{.M1}} := new([]model.{{.M2}})
	db := utils.DB
	if page.Name != "" {
		db = db.Where("name = ?", page.Name)
	}
	total := db.Scopes(utils.Paginate(page.PageNum, page.PageSize)).Find(&{{.M1}}).RowsAffected
	if total > 0 {
		return {{.M1}}, total
	} else {
		return nil, 0
	}
}

// Del{{.M2}} 删除数据
func (us *{{.M1}}Service) Delete{{.M2}}(id string, userId string) (err error) {
	{{.M1}}, errN := us.Get{{.M2}}ById(id)
	if errN != nil {
		return errN
	}
	{{.M1}}.DeleteId = userId
	err = utils.DB.Delete(&{{.M1}}, "id = ?", id).Error
	return err
}
// Remove{{.M2}} 永久删除数据
func (us *{{.M1}}Service) Remove{{.M2}}(id string) (err error) {
	{{.M1}} := new(model.{{.M2}})
	err = utils.DB.Unscoped().Delete(&{{.M1}}, "id = ?", id).Error
	return err
}
`
